<!-- This is a test for crbug.com/392765, in which Copy image for
     WebGL elements were crashing. Must be run with the threaded
     compositor enabled. -->
<head>
<script src="../../resources/js-test.js"></script>
<script>

function main()
{
  if (!window.testRunner) {
    testFailed("Requires window.testRunner");
  } else {
    testRunner.waitUntilDone();
    testRunner.dumpAsText();
    window.requestAnimationFrame(initTest);
  }
}

var tolerance = 1;

function initTest() {
  var canvas = document.getElementById("c");
  var gl = canvas.getContext("webgl");
  if (!gl) {
    testFailed("Test requires WebGL");
    testRunner.notifyDone();
    return;
  }

  gl.clearColor(1, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  window.requestAnimationFrame(runTest);
}

function runTest() {
  try {
    testRunner.copyImageThen(50, 50, completionCallback);
  } catch (e) {
    debug('error in runTest');
    debug(e);
    testRunner.notifyDone();
  }
}

var pixel;
function fetchPixelAt(x, y, width, height, snapshot) {
  var data = new Uint8Array(snapshot);
  pixel = [
    data[4 * (width * y + x) + 0],
    data[4 * (width * y + x) + 1],
    data[4 * (width * y + x) + 2],
    data[4 * (width * y + x) + 3]
  ];
}

function completionCallback(width, height, snapshot) {
  try {
    fetchPixelAt(50, 50, width, height, snapshot);
    shouldBeCloseTo('pixel[0]', 255, tolerance);
    shouldBeCloseTo('pixel[1]', 0, tolerance);
    shouldBeCloseTo('pixel[2]', 0, tolerance);
  } catch (e) {
    debug('error in completionCallback');
    debug(e);
    testRunner.notifyDone();
    return;
  }
  testRunner.notifyDone();
}

main();
</script>
</head>
<body>
<canvas id="c" width="200" height="200" class="nomargin"></canvas>
<div id="console"></div>
</body>
